<template>
	<view class="container">
		<view class="content">
			<!-- 如果页面中的cell高度是固定不变的，则不需要设置cell-height-mode，如果页面中高度是动态改变的，则设置cell-height-mode="dynamic" -->
			<!-- 原先的v-model修改为@virtualListChange="virtualListChange"并赋值处理后的虚拟列表 -->

			<z-paging ref="paging" :auto="false" defaultPageSize=30 use-virtual-list :force-close-inner-list="true"
				:paging-style="pagingStyle" cell-height-mode="dynamic" @virtualListChange="virtualListChange" @query="queryList">
				<!-- 需要固定在顶部不滚动的view放在slot="top"的view中，如果需要跟着滚动，则不要设置slot="top" -->
				<template #top>
					<nav-bar :tabList="tabList" @initNav="initNav" @change="change"></nav-bar>
					<view class="notice-box">
						<notice-bar></notice-bar>
					</view>
				</template>
				
				<!-- <view class="swiper-box" :style="swiperStyle"> -->
					<!-- <swiper class="swiper" :current="current" @animationfinish="swiperAnimationfinish"> -->
						<!-- <swiper-item class="swiper-item"> -->
							<peiwan v-show="isOnlineTab" class="swiper-item-online" :stickyTop="paddingTop" :scrollTop="scrollTop" :virtualList="virtualList" @mounted="onComponentMounted"></peiwan>
						<!-- </swiper-item> -->
						<!-- <swiper-item class="swiper-item"> -->
							<friend v-show="isNearTab" class="swiper-item-near" :stickyTop="paddingTop" :scrollTop="scrollTop" :virtualList="virtualList"  @mounted="onComponentMounted"></friend>
						<!-- </swiper-item> -->
					<!-- </swiper> -->
				<!-- </view> -->

			</z-paging>

		</view>
	</view>
</template>

<script>
	import NoticeBar from '@/pages/tabbar/components/home/noticeBar.vue';
	import NavBar from '@/pages/tabbar/components/home/navBar.vue';
	import peiwan from '@/pages/tabbar/components/home/peiwan.vue';
	import friend from '@/pages/tabbar/components/home/friend.vue';
	import sheep from '@/sheep';
	import ClerkApi from '@/sheep/api/worker/clerk';
	import UserApi from '@/sheep/api/member/user';
	import TradeConfigApi from '@/sheep/api/trade/config';
	export default {
		components: {
			NoticeBar,
			NavBar,
			peiwan,
			friend
		},
		props: {

		},
		data() {
			return {
				// 虚拟列表数组，通过@virtualListChange监听获得最新数组
				virtualList: [],
				scrollTop: 0,
				paddingTop: 0,
				paddingBottom: 100,
				heightArr:[550,550],
				height: 0,
				cityShow: false,
				scrollable: true,
				params: {
					province: true,
					city: true,
					area: false
				},
				tabList: [{
						name: '在线',
						enabled: false,
						type: 'online',
					},
					{
						name: '附近',
						enabled: false,
						type: 'near',
					},
					{
						name: '陪我',
						enabled: false,
						type: 'peiwan',
					}
				],

				tabType: '',

				queryParams: {
					pageNo: 1,
					pageSize: 20,
					sex: '',
					city: '',
					isCity: 1,
					maxAge: 50,
					minAge: 18,
					keyword: '',
					categoryId: '',
				},
				// 添加数据缓存
				cachedData: {
					online: {},
					near: {}
				},
				// 添加加载状态
				loading: false,
				switching: false, // 添加切换状态标记
			}
		},
		computed: {
			userInfo: {
				get() {
					return sheep.$store('user').userInfo;
				},
			},
			current: {
				get() {
					return sheep.$store('sys').homeTabIndex;
				},
			},
			pagingStyle() {
				return { 
					paddingTop: this.paddingTop + 'px', 
					paddingBottom: this.paddingBottom + 'rpx',
					justifyContent: 'center' 
				}
			},
			
			swiperStyle() {
				return {
					height: this.heightArr[this.current] + 'px',
					transition: 'height 0.3s ease-in-out'
				}
			},

			isOnlineTab() {
				return this.tabType === 'online'
			},

			isNearTab() {
				return this.tabType === 'near'
			}
		},
		created() {
			this.getTradeConfig();
		},
		methods: {
			initNav(e) {
				this.height = e.height;
				this.paddingTop = this.height;
			},
			// 监听虚拟列表数组改变并赋值给virtualList进行重新渲染
			virtualListChange(vList) {
				// 确保虚拟列表数据中每项都有 default 属性
				this.virtualList = vList.map(item => ({
					...item,
					default: item.default === undefined ? false : item.default
				}));
			},
			queryList(pageNo, pageSize) {
				// 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				// 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				// 模拟请求服务器获取分页数据，请替换成自己的网络请求
				this.queryParams.pageNo = pageNo;
				this.queryParams.pageSize = pageSize;
				this.queryParams.userId = this.userInfo.id;
				this.getDataPageList(this.queryParams);
			},
			getDataPageList(params) {
				if (this.loading) return
				this.loading = true				
				try {
					// 检查缓存
					const cacheKey = `${this.tabType}_${params.pageNo}`
					if (this.cachedData[this.tabType][cacheKey]) {
						const cachedData = this.cachedData[this.tabType][cacheKey]
						this.$refs.paging.complete(cachedData)
						return
					}
					const handlers = {
						online: () => ClerkApi.getClerkPage(params),
						near: () => {
							if (!params.sex) {
								params.sex = this.userInfo.sex
							}
							return UserApi.getUserPage(params)
						}
					}
					const handler = handlers[this.tabType]
					if (!handler) return
				
					handler()
						.then(res => {
							this.queryParams.keyword = ''
							// 缓存数据
							this.cachedData[this.tabType][cacheKey] = res.data.list
							this.$refs.paging.complete(res.data.list)
						})
						.catch(() => {
							this.$refs.paging.complete(false)
						})
				} finally {
					this.loading = false
				}
			},
			// 获取内容高度
			getCurrentSwiperHeight(element) {
				const query = uni.createSelectorQuery().in(this)
				query.select(element).boundingClientRect(data => {
					if(!data) return
					this.heightArr[this.current] = 10 + data.height
				}).exec()
			},		 
			// swiper滑动结束
			swiperAnimationfinish(e) {
				const { current } = e.detail
				if(current === this.current) return
				// 清除虚拟列表数据
				this.virtualList = []
				
				// 清除分页组件的数据
				this.$refs.paging.complete([])
				this.change(current)
			},
			change(e) {
				if (this.switching) return
				this.switching = true
				
				sheep.$store('sys').setHomeTabIndex(e);
				this.tabChange();	
				this.scrollTop = 0;
				this.queryParams.sex = "";
				sheep.$store('sys').setSexLabel("性别");
				
				const targetType = this.tabList[e]?.type
				if (targetType) {
					this.clearCache(targetType)
				}
				
				this.$refs.paging.reload()
				
				// 延迟重置切换状态
				setTimeout(() => {
					this.switching = false
				}, 300)
			},
			tabChange() {
				this.tabList = this.tabList.filter(function(tab) {
					return tab.enabled;
				});
				if (this.tabList[this.current]) {
					this.tabType = this.tabList[this.current].type;
				} else {
					sheep.$store('sys').setHomeTabIndex(0);
					this.tabType = this.tabList[0].type;
				}
			},
			getTradeConfig() {
				TradeConfigApi.getTradeConfig().then(res => {
					this.tabList[0].enabled = res.data.peiwanEnabled;
					this.tabList[1].enabled = res.data.friendEnabled;
					this.tabChange();
					this.$refs.paging.reload();
				});
			},
			tabClick(e) {
				console.log(e)
				if ('city' == e) {
					this.cityShow = true;
				} else if ('sex2' == e) {
					this.$refs.sex2Sheet.openActionSheet();
				} else if ('sex' == e) {
					this.$refs.sexSheet.openActionSheet();
				} else if ('category' == e) {
					this.$refs.categorySheet.openActionSheet();
				} else if ('level' == e) {

				}
			},
			search(e) {
				this.queryParams.keyword = e;
				this.$refs.paging.reload();
			},
			categoryOk(e) {
				sheep.$store('sys').setCategoryLabel(e.label);
				this.queryParams.categoryId = e.value;
				this.$refs.paging.reload();
			},
			cityOk(e) {
				this.cityShow = false;
				this.queryParams.city = e.city_name;
				sheep.$store('sys').setCityLabel(e.city_name);
				this.$refs.paging.reload();
			},
			categoryClick(e) {
				sheep.$store('sys').setCategoryLabel(e.name);
				this.queryParams.categoryId = e.id;
				this.$refs.paging.reload();
			},
			sexOk(e) {
				sheep.$store('sys').setSexLabel(e.label);
				this.queryParams.sex = e.value;
				this.$refs.paging.reload();
			},
			sex2Ok(e) {
				sheep.$store('sys').setSex2Label(e.label);
				this.queryParams.sex = e.value;
				this.$refs.paging.reload();
			},
			queryUser(e) {
				this.queryParams.sex = e.sex;
				this.queryParams.isCity = e.isCity;
				this.queryParams.maxAge = e.maxAge;
				this.queryParams.minAge = e.minAge;
				this.queryParams.city = e.city;
				this.$refs.paging.reload();
			},
			// 添加 peiwan 组件挂载完成的回调
			onComponentMounted() {
				this.$nextTick(() => {
					setTimeout(() => {
						this.getCurrentSwiperHeight('.swiper-item-' + this.tabType)
					}, 500)
				})
			},
			// 清除指定类型的缓存
			clearCache(type) {
				if (type) {
					this.cachedData[type] = {}				 
				} else {
					this.cachedData = {
						online: {},
						near: {}
					}					 
				}
			},
		},
		// 添加生命周期钩子
		beforeDestroy() {
			// 组件销毁前清除所有缓存
			this.clearCache()
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: var(--bg-main);
		height: calc(100vh);
		padding-bottom: env(safe-area-inset-bottom);

		.notice-box {
			margin: 15px;
		}

		.swiper-box {
			.swiper {
				width: 100%;
				height: 100%;
				
				.swiper-item {
					overflow: hidden;
				}
			}
		}
	}
</style>